/**
 * @product: AFP
 * @copyright: FSAI-南征北战信息科技
 * @filename: com.sod.interceptor.AuthorityInterceptor.java
 *
 * @link: Http://www.fastsai.com
 * @jdkv: Jdk 1.8
 */
package com.fsai.cms.config;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用戶登录验证拦截器
 * 
 * @project: sod-web-admin
 *
 * @author: JaffeHe
 * @email: JaffeHe@foxmail.com
 * @date: 2020-06-05 22:01
 *
 * @ChangeLog<br/>
 * 				Developer Date Comment <br/>
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	@Value("${cms.auth.enabled}")
	private Boolean enabledAuth;

	/**
	 * 在请求处理之前进行调用（Controller方法调用之前）
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String uri = request.getRequestURI();
		log.info("----------拦截请求地址---------" + uri);
		//输出相关参数
		@SuppressWarnings("rawtypes")
		Enumeration enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			log.info("请求参数---" + paraName + ": " + request.getParameter(paraName));
		}

		if (!enabledAuth) {
			return true;
		}

		//携带参数ADM
		if (uri.indexOf("ADM") > 0) {
			return true;
		} else {
			response.sendRedirect(request.getContextPath() + "/admin/login");//跳转到未授权页面
			return false;
		}

	}

	/**
	 * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv)
			throws Exception {
	}

	/**
	 * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行 （主要是用于进行资源清理工作）
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex)
			throws Exception {
	}

}
